#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<pthread.h>

#define NUM 5000

//创建一把互斥锁
pthread_mutex_t mutex;

int number = 0;

void *mythread(void *arg)
{
	int i = 0;
	int n ;
	for( i=0;i<NUM;i++)
	{
		//加锁
		pthread_mutex_lock(&mutex);
	
		n = number;
		n++;
		number = n;
		printf("1:[%d]\n",number);

		//解锁
		pthread_mutex_unlock(&mutex);
	}
}
void *mythread2(void *arg)
{
	int i=0;
	int n;
	for( i=0;i<NUM;i++)
	{
		pthread_mutex_lock(&mutex);
		n = number;
		n++;
		number = n;
		printf("2:[%d]\n",number);
		pthread_mutex_unlock(&mutex);
	}
}
int main()
{
	//初始化一把锁
	pthread_mutex_init(&mutex,NULL);


	//创建线程
	pthread_t thread1;
	int res = pthread_create(&thread1,NULL,mythread,NULL);
	//pthread_detach(thread1);
	if(res != 0)
	{
		printf("thread_creat error,[%s]\n",strerror(res));
		return -1;
	}

	pthread_t thread2;
	res = pthread_create(&thread2,NULL,mythread2,NULL);
	//pthread_detach(thread2);
	if(res != 0)
	{
		printf("thread_creat error,[%s]\n",strerror(res));
		return -1;
	}
	
	pthread_join(thread1,NULL);
	pthread_join(thread2,NULL);
	//释放互斥锁
	pthread_mutex_destroy(&mutex);
	//sleep(10);
	printf("number==[%d]\n",number);

	return 0;
}
